package pers.vicxu.mvcrestplus.dao;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;
import pers.vicxu.mvcrestplus.pojo.Book;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

/**
 * Create by Vic Xu on 7/26/2018
 *
 * @author Vic Xu
 */
@Repository
public class BookDaoImpl implements BookDao {

    @PersistenceContext(name = "em")
    private EntityManager entityManager;


    @Value("from Book")
    private String queryAllBooksSql;


    @Override
    public List<Book> findAll() {
        return entityManager.createQuery(queryAllBooksSql).getResultList();
    }

    @Override
    public Book addBook(Book book) {
        entityManager.persist(book);
        return book;
    }

    @Override
    public boolean deleteBook(String key) {
        Book book = entityManager.getReference(Book.class, key);
        if (book != null) {
            entityManager.remove(book);
            return true;
        }
        return false;
    }

    @Override
    public Book updateBook(Book book) {
        Book book1 = entityManager.getReference(Book.class, book.getId());
        book1.setAuthor(book.getAuthor());
        book1.setbName(book.getbName());
        book1.setPrice(book.getPrice());
        return book1;
    }
}
